<template>
  <div class="setting">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="main">
        <el-row>
          <el-col class="user_form" :span="12" v-loading="loading">
            <el-form
              ref="form"
              :model="userInfo"
              label-width="80px"
              :rules="rules"
            >
              <el-form-item label="编号">
                {{ userInfo.id }}
              </el-form-item>
              <el-form-item label="手机">
                {{ userInfo.mobile }}
              </el-form-item>
              <el-form-item label="媒体名称" prop="name">
                <el-input v-model="userInfo.name"></el-input>
              </el-form-item>

              <el-form-item label="媒体介绍" prop="intro">
                <el-input type="textarea" v-model="userInfo.intro"></el-input>
              </el-form-item>

              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfo.email"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="updateUserInfo"
                  >保存设置</el-button
                >
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="4" :offset="4">
            <div class="demo-fit">
              <div @click="$refs.file.click()">
                <el-avatar
                  shape="square"
                  :size="100"
                  fit="cover"
                  :src="userInfo.photo"
                ></el-avatar>
                <p class="txt">修改头像</p>
              </div>
              <input type="file" ref="file" hidden @change="onFileChange" />
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-dialog
      title="修改图像"
      :visible.sync="centerDialogVisible"
      width="30%"
      :append-to-body="true"
      center
      @opened="onDialog"
      @closed="closedDialog"
    >
      <div class="cropper">
        <img :src="url" alt="" width="150" ref="cropper_img" />
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="updateImage"
          :loading="isloading"
          :disabled="loading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import globalBus from "@/utils/global-bus";
import {
  getUserDetail,
  updateUserPhoto,
  updateUserProfile,
} from "@/request/api.js";

export default {
  name: "MySetting",
  data() {
    return {
      centerDialogVisible: false,
      userInfo: {
        id: "",
        mobile: "",
        name: "",
        intro: "",
        email: "",
        photo: "",
      },
      url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
      cropper: null, // 剪裁器
      isloading: false,
      loading: false,

      rules: {
        name: [
          {
            required: true,
            message: "请输入活动名称",
            trigger: "change",
            min: 1,
          },
        ],
        intro: [
          {
            required: true,
            message: "请输入内容",
            trigger: "change",
            min: 1,
          },
        ],

        email: [
          {
            message: "请输入邮箱",
            required: true,
            trigger: "change",
          },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  created() {
    getUserDetail().then((res) => {
      console.log("用户", res.data);
      this.userInfo = res.data.data;
    });
  },

  methods: {
    onFileChange() {
      const file = this.$refs.file;

      // 图片预览
      const blobData = window.URL.createObjectURL(file.files[0]);
      this.url = blobData;

      this.centerDialogVisible = true;

      this.$refs.file.value = "";
    },

    onDialog() {
      if (this.cropper) {
        this.cropper.replace(this.url);
        return;
      }
      const image = this.$refs["cropper_img"];
      this.cropper = new Cropper(image, {
        aspectRatio: 16 / 9,
      });
    },

    closedDialog() {
      // this.cropper.destroy()
    },

    updateImage() {
      this.isloading = true;
      this.cropper.getCroppedCanvas().toBlob((file) => {
        const fd = new FormData();
        fd.append("photo", file);

        updateUserPhoto(fd).then((res) => {
          console.log("更新头像", res);

          this.centerDialogVisible = false;
          this.isloading = false;
          this.userInfo.photo = res.data.data.photo;
          globalBus.$emit("update-img", res.data.data.photo);
        });
      });
    },

    // 修改用户

    updateUserInfo() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
        
          this.loading = true;

          let { name, intro, email } = this.userInfo;
          updateUserProfile({
            name,
            intro,
            email,
          })
            .then((res) => {
              console.log("修改用户成功", res.data);
              this.loading = false;
              this.$message({
                message: "保存成功",
                type: "success",
              });

              globalBus.$emit("update-user", res.data.data);
            })
            .catch(() => {
              this.loading = false;
              this.$message({
                showClose: true,
                message: "修改失败",
                type: "error",
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  padding: 0 20px;
  // .txt{
  //     text-align: center;
  // }
}
.demo-fit {
  display: flex;
  flex-direction: column;
  align-items: center;
  .txt {
    padding: 10px 0;
    text-align: center;
  }
}
// .main {
//   display: flex;
// //   .user_form,
// //   .user_img {
// //     width: 50%;
// //   }
// //   .user_img {
// //     display: flex;
// //     justify-content: center;
// //     //   align-items: center;
// //     .user_img_box {
// //     }
// //   }
// //   .txt {
// //     text-align: center;
// //   }
// }

.cropper {
  > img {
    display: block;
    max-width: 100%;
    height: 200px;
  }
}
</style>
